package adnroid.asynchronous.demo;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Demo02AsyncTaskUpdateUIActivity extends Activity {

	private Button btnDownload = null;
	private ImageView imgViewDownload = null;
	private ProgressBar pbDownload = null;
	@SuppressWarnings("rawtypes")
	private AsyncTask asyncTask = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.demo02_asynctask_update_ui);
		
		imgViewDownload = (ImageView)this.findViewById(R.id.imgViewDownload);
		pbDownload = (ProgressBar)this.findViewById(R.id.pbDownload);
		
		btnDownload.setOnClickListener(new View.OnClickListener() {
			
			@SuppressWarnings("unchecked")
			public void onClick(View v) {
				asyncTask.execute("http://avatar.csdn.net/0/3/4/1_mylzc.jpg");
			}
		});
		
		asyncTask = new AsyncTask<String, Integer, Bitmap>() {

			@Override  
	        protected Bitmap doInBackground(String... params) {
	            publishProgress(0);
	            HttpClient hc = new DefaultHttpClient();  
	            publishProgress(30);  
	            HttpGet hg = new HttpGet(params[0]);
	            final Bitmap bm;  
	            try {  
	                HttpResponse hr = hc.execute(hg);  
	                bm = BitmapFactory.decodeStream(hr.getEntity().getContent());  
	            } catch (Exception e) {  
	                  
	                return null;  
	            }  
	            publishProgress(100);  
	            //mImageView.setImageBitmap(result); 
	            return bm;  
	        }  
	          
	        protected void onProgressUpdate(Integer... progress) {
	            pbDownload.setProgress(progress[0]);
	         }  
	  
	         protected void onPostExecute(Bitmap result) {
	             if(result != null) {  
	                 Toast.makeText(Demo02AsyncTaskUpdateUIActivity.this, "�ɹ���ȡͼƬ", Toast.LENGTH_LONG).show();  
	                 imgViewDownload.setImageBitmap(result);  
	             }else {  
	                 Toast.makeText(Demo02AsyncTaskUpdateUIActivity.this, "��ȡͼƬʧ��", Toast.LENGTH_LONG).show();  
	             }  
	         }  
	           
	         protected void onPreExecute () {
	        	 imgViewDownload.setImageBitmap(null);  
	        	 pbDownload.setProgress(0);
	         }  
	           
	         protected void onCancelled () {
	        	 pbDownload.setProgress(0);
	         }  
		};
	}

}
